<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/3/6
 * Time: 上午10:32
 */

namespace app\admin\controller\v1;

use app\admin\controller\Fun;
use app\common\Model\Order;
use app\common\Model\OrderInfoShaohuo;
use app\admin\service\ShaohuoOrderService;
use app\common\Model\UserShaohuoFuncs;
use think\Config;
use think\Db;

/**
 * @title 后台-捎货订单管理
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class ShaoHuoOrder extends Base
{
    protected $model;

    public function __construct($param)
    {
        parent::__construct($param);
        $this->model = model('app\common\Model\OrderInfoShaohuo');
    }

    /**
     * @title 捎货订单列表
     * @description
     * @author jikesen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaoHuoOrder desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:listOrder desc:捎货订单列表
     * 
     * @param name:page type:string require:1 default: other: desc:页码
     * @param name:page_size type:string require:1 default: other: desc:每页个数
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:district type:string require:1 default: other: desc:订单归属地(区域ID)
     * @param name:orderType type:string require:1 default:1 other: desc:捎货类型
     * @param name:orderStatus type:string require:1 default: other: desc:订单状态
     * @param name:isShipping type:string require:1 default: other: desc:是否指派捎货人(0:未指派,1:有指派)
     * @param name:orderStime type:string require:1 default: other: desc:下单开始查询时间
     * @param name:orderEtime type:string require:1 default: other: desc:下单结束查询时间
     * @param name:preSendStime type:string require:1 default: other: desc:预计送达开始查询时间
     * @param name:preSendEtime type:string require:1 default: other: desc:预计送达结束查询时间
     * @param name:receiveStime type:string require:1 default: other: desc:接单开始查询时间
     * @param name:receiveEtime type:string require:1 default: other: desc:接单结束查询时间
     * @param name:sendStime type:string require:1 default: other: desc:送达开始查询时间
     * @param name:sendEtime type:string require:1 default: other: desc:送达结束查询时间
     *
     * @return data:[]
     */
    public function listOrder()
    {
        //查询
        $where = [];
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['s.order_num|s.trade_no|s.func_name|s.remark'] = ['like', '%' . $search . '%'];
        }
        //捎货类型
        if (isset($this->param['orderType']) && $this->param['orderType'] != '') {
            $where['s.fc_id'] = intval($this->param['orderType']);
        }
        //订单状态
        if (isset($this->param['orderStatus']) && $this->param['orderStatus'] != '') {
            $where['s.status'] = intval($this->param['orderStatus']);
        }
        //是否指派捎货人
        if (isset($this->param['isShipping']) && $this->param['isShipping'] != '') {
            if ($this->param['isShipping']==0) {
                $where['s.shipping_uid'] = 0;
            }else{
                $where['s.shipping_uid'] = array('neq',0);
            }
        }
        //订单归属地
        if (isset($this->param['district']) && $this->param['district'] != '') {
            $where['s.region_id'] = intval($this->param['district']);
        }        
        //预计送达时间
        if (isset($this->param['preSendStime']) && $this->param['preSendStime'] != '') {
            $where['s.book_time'] = array('egt',$this->param['preSendStime']);
        }
        if (isset($this->param['preSendEtime']) && $this->param['preSendEtime'] != '') {
            if (isset($where['s.book_time'])) {
                 $where['s.book_time'] = array('between',[$this->param['preSendStime'],$this->param['preSendEtime']]);
            } else {
                $where['s.book_time'] = array('elt',$this->param['preSendEtime']);
            }
        }

        $where_time = [];
        $join = [];
        //下单时间
        if (isset($this->param['orderStime']) && $this->param['orderStime'] != '') {
            $join = [
                ['order_action_shaohuo o','o.order_id=s.order_id','left'],
            ];
            $where_time['o.type'] = 1;
            $where_time['o.create_time'] = array('egt',$this->param['orderStime']);
        }
        if (isset($this->param['orderEtime']) && $this->param['orderEtime'] != '') {
            $join = [
                ['order_action_shaohuo o','o.order_id=s.order_id','left'],
            ];
            $where_time['o.type'] = 1;
            if (isset($where_time['o.create_time'])) {
                 $where_time['o.create_time'] = array('between',[$this->param['orderStime'],$this->param['orderEtime']]);
            } else {
                $where_time['o.create_time'] = array('elt',$this->param['orderEtime']);
            }
        }

        $where_time2 = [];
        $join2 = [];
        //接单时间
        if (isset($this->param['receiveStime']) && $this->param['receiveStime'] != '') {
            $join2 = [
                ['order_action_shaohuo oa','oa.order_id=s.order_id','left'],
            ];
            $where_time2['oa.type'] = 4;
            $where_time2['oa.create_time'] = array('egt',$this->param['receiveStime']);
        }
        if (isset($this->param['receiveEtime']) && $this->param['receiveEtime'] != '') {
            $where_time2['oa.type'] = 4;
            $join2 = [
                ['order_action_shaohuo oa','oa.order_id=s.order_id','left'],
            ];
            if (isset($where_time2['oa.create_time'])) {
                 $where_time2['oa.create_time'] = array('between',[$this->param['receiveStime'],$this->param['receiveEtime']]);
            } else {
                $where_time2['oa.create_time'] = array('elt',$this->param['receiveEtime']);
            }
        }

        $where_time3 = [];
        $join3 = [];
        //送达时间
        if (isset($this->param['sendStime']) && $this->param['sendStime'] != '') {
            $where_time3['os.type'] = 6;
            $join3 = [
                ['order_action_shaohuo os','os.order_id=s.order_id','left'],
            ];            
            $where_time3['os.create_time'] = array('egt',$this->param['sendStime']);
        }
        if (isset($this->param['sendEtime']) && $this->param['sendEtime'] != '') {
            $where_time3['os.type'] = 6;
            $join3 = [
                ['order_action_shaohuo os','os.order_id=s.order_id','left'],
            ];            
            if (isset($where_time3['os.create_time'])) {
                 $where_time3['os.create_time'] = array('between',[$this->param['sendStime'],$this->param['sendEtime']]);
            } else {
                $where_time3['os.create_time'] = array('elt',$this->param['sendEtime']);
            }
        }

        //可排序字段
        $used_sort_field = [
            'order_num',
            'status',
            'id',
            'order_id',
            'serve_ua_id',
            'item_name',
            'shname',
            'nick_name',
            'mobile',
            'create_time',
            'book_time',
            'goods_price',
            'shipping_fee',
        ];

        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['s.id' => $this->sort_type[1]];
        }

        $list = Db::name('order_info_shaohuo s')
            ->join($join)
            ->join($join2)
            ->join($join3)
            ->join('user u', 'u.uid=s.uid', 'left')
            ->join('user us', 'us.uid=s.shipping_uid', 'left')
            ->where($where)
            ->where($where_time)
            ->where($where_time2)
            ->where($where_time3)
            ->order($order)
            ->field('
            s.id,
            s.order_id,
            s.order_num,
            s.func_name,
            s.status,
            s.serve_ua_id,
            s.item_name,
            us.nick_name as shname,
            u.nick_name,
            u.mobile,
            s.create_time,
            s.book_time,
            s.goods_price,
            s.shipping_fee,
            s.end_addr,
            s.video_time,
            s.region_id
            ')
            ->group('s.order_id')
            ->paginate($this->page_size, false, ['page' => $this->param['page']]);
        if ($list) {
            //订单状态
            $su_status = $this->model->_status;
            $data = [];
            foreach ($list->items() as $key => $value) {
                $value['status'] = $su_status[$value['status']];
                //归属地
                $start_addr = Db::name('region')
                    ->where(['region_id'=>$value['region_id']])
                    ->field('name')
                    ->find();
                if (!empty($start_addr)) {
                    $value['start_addr'] = $start_addr['name'];
                }else{
                    $value['start_addr'] = '';
                }

                //如果是语音文件 拼接完整路径
                if($value['video_time'] != -1){
                    $voice_url = Config::get('aliyun_oss.img_url');
                    $value['item_name'] = $voice_url . $value['item_name'];
                }                    
                unset($value['video_time']);
                if (empty($value['shname'])) {
                    $value['shname'] = '自由接单';
                }

                //接单时间
                $jiedan = Db::name('order_action_shaohuo')
                ->where(['order_id'=>$value['order_id'],'type'=>4])
                ->field('create_time')
                ->find();
                

                //查询订单最新归属人
                $value['guishu'] = Db::name('order_action_shaohuo oas')
                    ->join([
                        ['user u', 'u.uid=oas.deal_uid'],
                    ])
                    ->where(['oas.order_id'=>$value['order_id']])
                    ->field('u.nick_name,u.mobile,oas.create_time')
                    ->order('oas.create_time desc')
                    ->find();
                $value['guishu']['create_time'] = $jiedan['create_time'];

                $value['goods_price'] = sprintf("%.2f",$value['goods_price'] / 100);
                $value['shipping_fee'] = sprintf("%.2f",$value['shipping_fee'] / 100);

                //查询订单收件人
                $addr = json_decode($value['end_addr'],true);
                unset($value['end_addr']);
                $arrive = Db::name('order_action_shaohuo')
                    ->where(['order_id'=>$value['order_id'],'type'=>6])
                    ->field('create_time')
                    ->find();
                $addr['time'] = $arrive['create_time'];
                $value['shoujian'] = $addr;
                $data[] = $value;
            }
            return Fun::success(['list' => $data, 'total_num' => $list->total()]);
        } else {
            return Fun::error('333333');
        }
    }

    /**
     * @title 捎货人列表
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaoHuoOrder desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * 
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:shaohuoUserList desc:捎货人列表
     *
     * @return data:[]
     */
    public function shaohuoUserList()
    {
        $users = Db::name('user_shaohuo s')
        ->join([
            ['user u', 'u.uid=s.uid'],
        ])
        ->where(['s.status'=>1])
        ->field('u.uid,u.nick_name,u.mobile')
        ->select();       
        if ($users) {
            return Fun::success(['list' => $users]); 
        }else{
            return Fun::error('333333');
        }
    }

    /**
     * @title 修改订单捎货人
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaoHuoOrder desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * 
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:modiShipping desc:修改订单捎货人
     * @param name:us_id type:string require:1 default: other: desc:捎货人ID(修改为自由接单人时传0)
     * @param name:list_id type:string require:1 default: other: desc:订单列表ID
     * @return data:[]
     */
    public function modiShipping()
    {
        $shipping_uid = $this->param['us_id'];
        $order_id = $this->param['list_id'];
        $lat = $this->param['lat'] ?? '';
        $lng = $this->param['lng'] ?? '';

        //查询订单详情
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id]);

        if(empty($order_info)){
            return Fun::error('801013');
        }

        //看是否已经被接单过
        $search  = DB::name('order_action_shaohuo')->where(['order_id'=>$order_id,'type'=>4])->find();
        if (empty($search)) {
            if($order_info->status != 2){
                //无效订单
                return Fun::error('801019');
            }
        }

        $fc_id = $order_info->fc_id;
        switch ($fc_id)
        {
            case 1:
                $status = 4;
                break;
            case 2:
                $status = 3;
                break;
            default:
                $status = 6;
        }

        //查询用户权限
        $rtn = UserShaohuoFuncs::get([
            'uid' => $shipping_uid,
            'fc_id' => $fc_id,
            'status' => 1,
            'user_status' => 1
        ]);

        if(empty($rtn)){
            //没有权限
            return Fun::error('801020');
        }

        Db::startTrans();
        try{
            //修改捎货人信息
            OrderInfoShaohuo::where([
                'order_id' => $order_id,
                'status' => 2
            ])->update([
                'shipping_uid' => $shipping_uid,
                'status' => $status
            ]);

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,4,$shipping_uid,'');
            Db::commit();
            return Fun::success('接单成功');
        }catch (ErrorException $exception){
            Db::rollback();
            return Fun::error('801021');
        }
    }

    /**
     * @title 修改订单恢复自由接单
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaoHuoOrder desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * 
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:updateShipping desc:修改订单恢复自由接单
     * @param name:us_id type:string require:1 default: other: desc:捎货人ID(修改为自由接单人时传0)
     * @param name:list_id type:string require:1 default: other: desc:订单列表ID
     * @return data:[]
     */
    public function updateShipping()
    {
        $shipping_uid = $this->param['us_id'];
        $order_id = $this->param['list_id'];
        $lat = $this->param['lat'] ?? '';
        $lng = $this->param['lng'] ?? '';

        $user = DB::name('admin_user')->where(['acc_id'=>$this->param['acc_id']])->field('uid')->find(); 
        $uid = $user['uid'];

        //查询订单详情
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id]);

        if(empty($order_info)){
            return Fun::error('801013');
        }

        if(($order_info->fc_id == 1 && $order_info->status != 4) ||
            ($order_info->fc_id == 2 && $order_info->status != 3) ||
            ($order_info->fc_id >= 3 && $order_info->status != 6)
        ){
            return Fun::error('订单已取消,操作失败');
        }

       /* if($order_info->status == 3){
            //无效订单
            return Fun::error('订单已取消,操作失败');
        }

        if($order_info->status == 5 || $order_info->status == 6 || $order_info->status == 7 || $order_info->status == 8){
            //无效订单
            return Fun::error('订单状态无法进行该操作');
        }*/

        Db::startTrans();
        try{
            //修改捎货人信息
            OrderInfoShaohuo::where([
                'order_id' => $order_id
            ])->update([
                'shipping_uid' => 0,
                'status' => 2
            ]);

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,9,$uid,'');
            Db::commit();
            return Fun::success('操作成功');
        }catch (ErrorException $exception){
            Db::rollback();
            return Fun::error('801021');
        }
    }

    /**
     * @title 取消订单
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaoHuoOrder desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * 
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:cancelOrder desc:取消订单
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     *
     * @return data:[]
     */
    public function cancelOrder()
    {
        $order_id = $this->param['order_id'];
        $uid = $this->param['uid'];
        //查询订单信息
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id]);
        if(!$order_info){
            return Fun::error('801013');
        }

        //业务类型
        $func_id = $order_info->fc_id;

        if(empty($order_info)){
            return Fun::error('801013');
        }

        Db::startTrans();
        try{
            //待支付待应答允许取消
            if($order_info->status == 1){
                Order::where(['id' => $order_info->order_id])->update(['status' => 3]);
                OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 7]);
            }elseif ($order_info->status == 2){
                //TODO 退款逻辑
                Order::where(['id' => $order_info->order_id])->update(['status' => 4]);
                OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 7]);
            }else{
                Db::rollback();
                //禁止取消
                return Fun::error('801011');
            }

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,3,$uid);

            Db::commit();
            return Fun::success([],'取消成功');
        }catch (ErrorException $exception){
            Db::rollback();
            //取消失败
            return Fun::error('801012');
        }
    }

    /**
     * @title 订单数据导出
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaoHuoOrder desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:exportShaohuoOrder desc:订单数据导出
     *
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     * @param name:district type:string require:1 default: other: desc:订单归属地(区域ID)
     * @param name:orderType type:string require:1 default:1 other: desc:捎货类型
     * @param name:orderStatus type:string require:1 default: other: desc:订单状态
     * @param name:isShipping type:string require:1 default: other: desc:是否指派捎货人(0:未指派,1:有指派)
     * @param name:orderStime type:string require:1 default: other: desc:下单开始查询时间
     * @param name:orderEtime type:string require:1 default: other: desc:下单结束查询时间
     * @param name:preSendStime type:string require:1 default: other: desc:预计送达开始查询时间
     * @param name:preSendEtime type:string require:1 default: other: desc:预计送达结束查询时间
     * @param name:receiveStime type:string require:1 default: other: desc:接单开始查询时间
     * @param name:receiveEtime type:string require:1 default: other: desc:接单结束查询时间
     * @param name:sendStime type:string require:1 default: other: desc:送达开始查询时间
     * @param name:sendEtime type:string require:1 default: other: desc:送达结束查询时间
     *
     * @return data:[]
     */
    public function exportShaohuoOrder()
    {
        set_time_limit(0);
        ini_set('memory_limit', '2048M');

        //查询
        $where = [];
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['s.order_num|s.trade_no|s.func_name|s.remark'] = ['like', '%' . $search . '%'];
        }
        //捎货类型
        if (isset($this->param['orderType']) && $this->param['orderType'] != '') {
            $where['s.fc_id'] = intval($this->param['orderType']);
        }
        //订单状态
        if (isset($this->param['orderStatus']) && $this->param['orderStatus'] != '') {
            $where['s.status'] = intval($this->param['orderStatus']);
        }
        //是否指派捎货人
        if (isset($this->param['isShipping']) && $this->param['isShipping'] != '') {
            if ($this->param['isShipping']==0) {
                $where['s.shipping_uid'] = 0;
            }else{
                $where['s.shipping_uid'] = array('neq',0);
            }
        }
        //订单归属地
        if (isset($this->param['district']) && $this->param['district'] != '') {
            $where['s.region_id'] = intval($this->param['district']);
        }        
        //预计送达时间
        if (isset($this->param['preSendStime']) && $this->param['preSendStime'] != '') {
            $where['s.book_time'] = array('egt',$this->param['preSendStime']);
        }
        if (isset($this->param['preSendEtime']) && $this->param['preSendEtime'] != '') {
            if (isset($where['s.book_time'])) {
                 $where['s.book_time'] = array('between',[$this->param['preSendStime'],$this->param['preSendEtime']]);
            } else {
                $where['s.book_time'] = array('elt',$this->param['preSendEtime']);
            }
        }

        $where_time = [];
        $join = [];
        //下单时间
        if (isset($this->param['orderStime']) && $this->param['orderStime'] != '') {
            $join = [
                ['order_action_shaohuo o','o.order_id=s.order_id','left'],
            ];
            $where_time['o.type'] = 1;
            $where_time['o.create_time'] = array('egt',$this->param['orderStime']);
        }
        if (isset($this->param['orderEtime']) && $this->param['orderEtime'] != '') {
            $join = [
                ['order_action_shaohuo o','o.order_id=s.order_id','left'],
            ];
            $where_time['o.type'] = 1;
            if (isset($where_time['o.create_time'])) {
                 $where_time['o.create_time'] = array('between',[$this->param['orderStime'],$this->param['orderEtime']]);
            } else {
                $where_time['o.create_time'] = array('elt',$this->param['orderEtime']);
            }
        }

        $where_time2 = [];
        $join2 = [];
        //接单时间
        if (isset($this->param['receiveStime']) && $this->param['receiveStime'] != '') {
            $join2 = [
                ['order_action_shaohuo oa','oa.order_id=s.order_id','left'],
            ];
            $where_time2['oa.type'] = 4;
            $where_time2['oa.create_time'] = array('egt',$this->param['receiveStime']);
        }
        if (isset($this->param['receiveEtime']) && $this->param['receiveEtime'] != '') {
            $where_time2['oa.type'] = 4;
            $join2 = [
                ['order_action_shaohuo oa','oa.order_id=s.order_id','left'],
            ];
            if (isset($where_time2['oa.create_time'])) {
                 $where_time2['oa.create_time'] = array('between',[$this->param['receiveStime'],$this->param['receiveEtime']]);
            } else {
                $where_time2['oa.create_time'] = array('elt',$this->param['receiveEtime']);
            }
        }

        $where_time3 = [];
        $join3 = [];
        //送达时间
        if (isset($this->param['sendStime']) && $this->param['sendStime'] != '') {
            $where_time3['os.type'] = 6;
            $join3 = [
                ['order_action_shaohuo os','os.order_id=s.order_id','left'],
            ];            
            $where_time3['os.create_time'] = array('egt',$this->param['sendStime']);
        }
        if (isset($this->param['sendEtime']) && $this->param['sendEtime'] != '') {
            $where_time3['os.type'] = 6;
            $join3 = [
                ['order_action_shaohuo os','os.order_id=s.order_id','left'],
            ];            
            if (isset($where_time3['os.create_time'])) {
                 $where_time3['os.create_time'] = array('between',[$this->param['sendStime'],$this->param['sendEtime']]);
            } else {
                $where_time3['os.create_time'] = array('elt',$this->param['sendEtime']);
            }
        }

        //可排序字段
        $used_sort_field = [
            'order_num',
            'status',
            'id',
            'order_id',
            'serve_ua_id',
            'item_name',
            'shname',
            'nick_name',
            'mobile',
            'create_time',
            'book_time',
            'goods_price',
            'shipping_fee',
        ];

        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['s.id' => $this->sort_type[1]];
        }

        $list = Db::name('order_info_shaohuo s')
            ->join($join)
            ->join($join2)
            ->join($join3)
            ->join('user u', 'u.uid=s.uid', 'left')
            ->join('user us', 'us.uid=s.shipping_uid', 'left')
            ->where($where)
            ->where($where_time)
            ->where($where_time2)
            ->where($where_time3)
            ->order($order)
            ->field('
            s.order_id,
            s.order_num,
            s.func_name,
            s.status,
            s.item_name,
            us.nick_name as shname,
            u.nick_name,
            u.mobile,
            s.create_time,
            s.book_time,
            s.video_time,
            s.goods_price,
            s.shipping_fee,
            s.end_addr,
            s.region_id
            ')
            ->group('s.order_id')
            ->select();

        if ($list) {
            $fileName = './csv/' . date('YmdHis').'.csv';
            $headlist = ['运单号', '捎货类型','订单状态', '订单归属地', '商品信息', '是否指派捎货人', '下单人', '电话', '下单时间', '预约到达时间', '下单金额', '加价金额', '当前接单捎货人', '接单人电话', '接单时间', '收件人', '电话', '收件地址', '送达时间'];

            //订单状态
            $su_status = $this->model->_status;
            $data = [];
            foreach ($list as $key => $value) {
                $value['status'] = $su_status[$value['status']];
                //归属地
                $start_addr = Db::name('region')
                    ->where(['region_id'=>$value['region_id']])
                    ->field('name')
                    ->find();
                if (!empty($start_addr)) {
                    $value['start_addr'] = $start_addr['name'];
                }else{
                    $value['start_addr'] = '无';
                }
                unset($value['region_id']);
                //如果是语音文件 拼接完整路径
                if($value['video_time'] != -1){
                    $voice_url = Config::get('aliyun_oss.img_url');
                    $value['item_name'] = $voice_url . $value['item_name'];
                }                
                unset($value['video_time']);
                if (empty($value['shname'])) {
                    $value['shname'] = '自由接单';
                }

                //接单时间
                $jiedan = Db::name('order_action_shaohuo')
                ->where(['order_id'=>$value['order_id'],'type'=>4])
                ->field('create_time')
                ->find();

                //查询订单最新归属人
                $now = Db::name('order_action_shaohuo oas')
                    ->join([
                        ['user u', 'u.uid=oas.deal_uid'],
                    ])
                    ->where(['oas.order_id'=>$value['order_id']])
                    ->field('u.nick_name,u.mobile,oas.create_time')
                    ->order('oas.create_time desc')
                    ->find();
                $value['nowname'] = $now['nick_name'];
                $value['nowmobile'] = $now['mobile'];
                $value['nowcreate_time'] =$jiedan['create_time'];
                
                $value['goods_price'] = sprintf("%.2f",$value['goods_price'] / 100);
                $value['shipping_fee'] = sprintf("%.2f",$value['shipping_fee'] / 100);

                //查询订单收件人
                $addr = json_decode($value['end_addr'],true);
                unset($value['end_addr']);
                if (!empty($addr)) {
                    $value['sname'] = $addr['consignee'];
                    $value['sphone'] = $addr['mobile'];
                    $value['saddress'] = $addr['province'].$addr['city'].$addr['district'].$addr['address'].$addr['building'];
                }else{
                    $value['sname'] = $value['sphone'] = $value['saddress']= '';
                }
                $arrive = Db::name('order_action_shaohuo')
                    ->where(['order_id'=>$value['order_id'],'type'=>7])
                    ->field('create_time')
                    ->find();
                unset($value['order_id']);
                if ($arrive) {
                    $value['stime'] = $arrive['create_time'];
                }else{
                    $value['stime'] = '无';
                }
                $data[] = $value;
            }
            Fun::exportCsv($fileName,$headlist,$data);
            return Fun::success(['file_url'=>config('param.url').trim($fileName,'.')]);
        } else {
            return Fun::error('802002');//所选导出数据为空
        }
    }

}